package com.orcamento.converter;

import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;
import org.joda.time.DateTime;
import org.joda.time.IllegalInstantException;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.orcamento.util.CalendarUtil;

public class DateConverter extends StrutsTypeConverter {

	@SuppressWarnings("rawtypes")
	public Object convertFromString(Map context, String[] values, Class toClass) {
		try {
			 DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
			 return fmt.parseDateTime(values[0]); 
		} catch( IllegalInstantException e ) {
			 values[0] += " 01:00:00"; 
			 DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
			 return fmt.parseDateTime(values[0]);
		} catch(Exception e) {
			return values[0];
		}
	}

	@SuppressWarnings("rawtypes")
	public String convertToString(Map context, Object o) {
		return CalendarUtil.toString((DateTime) o, "dd/MM/yyyy");
	}
}
